import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useGameStore } from '@/store/game-store';
import { useBattleStore } from '@/store/battle-store';
import { 
  Sword, 
  Shield, 
  Zap, 
  Heart, 
  Star,
  Target,
  Flame,
  Snowflake,
  Wind,
  Mountain,
  Eye,
  Clock,
  TrendingUp,
  AlertTriangle,
  CheckCircle,
  RotateCcw,
  Play,
  Pause,
  Sparkles
} from 'lucide-react';

interface BattleAction {
  id: string;
  name: string;
  type: 'attack' | 'skill' | 'defend' | 'item';
  icon: React.ReactNode;
  description: string;
  damage?: number;
  manaCost?: number;
  cooldown?: number;
  effect?: string;
  color: string;
}

interface Enemy {
  id: string;
  name: string;
  level: number;
  health: number;
  maxHealth: number;
  mana: number;
  maxMana: number;
  attack: number;
  defense: number;
  speed: number;
  avatar: string;
  skills: string[];
  weakness?: string;
  resistance?: string;
  description: string;
}

interface DamageNumber {
  id: string;
  damage: number;
  type: 'damage' | 'heal' | 'miss' | 'critical';
  x: number;
  y: number;
}

export function BattlePage() {
  const { player, updatePlayer, addGold, skills } = useGameStore();
  const { 
    startBattle, 
    endBattle,
    resetBattle
  } = useBattleStore();

  // 战斗状态
  const [selectedAction, setSelectedAction] = useState<BattleAction | null>(null);
  const [battlePhase, setBattlePhase] = useState<'preparation' | 'combat' | 'victory' | 'defeat'>('preparation');
  const [turnCount, setTurnCount] = useState(1);
  const [isAnimating, setIsAnimating] = useState(false);
  const [damageNumbers, setDamageNumbers] = useState<DamageNumber[]>([]);
  const [autoMode, setAutoMode] = useState(false);
  const [battleTimer, setBattleTimer] = useState(0);
  const [battleLog, setBattleLog] = useState<string[]>([]);
  const [isPlayerTurn, setIsPlayerTurn] = useState(true);

  // 添加战斗日志函数
  const addLogEntry = (message: string) => {
    setBattleLog(prev => [...prev, message]);
  };

  // 敌人数据
  const [currentEnemy, setCurrentEnemy] = useState<Enemy>({
    id: 'demon_wolf',
    name: '魔狼',
    level: Math.max(1, player.level - 2 + Math.floor(Math.random() * 5)),
    health: 120,
    maxHealth: 120,
    mana: 40,
    maxMana: 40,
    attack: 25,
    defense: 8,
    speed: 15,
    avatar: '🐺',
    skills: ['撕咬', '嚎叫'],
    weakness: '火',
    resistance: '风',
    description: '森林深处的凶猛魔兽，拥有锋利的爪牙'
  });

  // 玩家当前状态
  const [playerBattleState, setPlayerBattleState] = useState({
    health: player.health,
    mana: player.mana,
    buffs: [] as Array<{name: string, turns: number, effect: string}>,
    debuffs: [] as Array<{name: string, turns: number, effect: string}>
  });

  // 战斗动作
  const battleActions: BattleAction[] = [
    {
      id: 'basic_attack',
      name: '普通攻击',
      type: 'attack',
      icon: <Sword className="h-4 w-4" />,
      description: '使用武器进行基础攻击',
      damage: player.attack,
      color: 'text-red-400'
    },
    {
      id: 'heavy_strike',
      name: '重击',
      type: 'skill',
      icon: <Target className="h-4 w-4" />,
      description: '消耗法力进行强力攻击',
      damage: Math.floor(player.attack * 1.5),
      manaCost: 15,
      color: 'text-orange-400'
    },
    {
      id: 'flame_slash',
      name: '烈焰斩',
      type: 'skill',
      icon: <Flame className="h-4 w-4" />,
      description: '火属性攻击，对某些敌人有额外伤害',
      damage: Math.floor(player.attack * 1.3),
      manaCost: 20,
      effect: '火',
      color: 'text-red-500'
    },
    {
      id: 'ice_spike',
      name: '冰刺术',
      type: 'skill',
      icon: <Snowflake className="h-4 w-4" />,
      description: '冰属性攻击，有几率冻结敌人',
      damage: Math.floor(player.attack * 1.2),
      manaCost: 18,
      effect: '冰',
      color: 'text-blue-400'
    },
    {
      id: 'wind_blade',
      name: '风刃',
      type: 'skill',
      icon: <Wind className="h-4 w-4" />,
      description: '风属性攻击，速度快命中率高',
      damage: Math.floor(player.attack * 1.1),
      manaCost: 12,
      effect: '风',
      color: 'text-green-400'
    },
    {
      id: 'defend',
      name: '防御',
      type: 'defend',
      icon: <Shield className="h-4 w-4" />,
      description: '提高防御力，减少受到的伤害',
      color: 'text-blue-400'
    },
    {
      id: 'meditation',
      name: '冥想',
      type: 'skill',
      icon: <Star className="h-4 w-4" />,
      description: '恢复法力值',
      manaCost: -25,
      color: 'text-purple-400'
    }
  ];

  // 敌人模板
  const enemyTemplates = [
    { name: '魔狼', avatar: '🐺', baseHealth: 120, baseAttack: 25, weakness: '火', resistance: '风' },
    { name: '石巨人', avatar: '🗿', baseHealth: 180, baseAttack: 20, weakness: '风', resistance: '火' },
    { name: '火蜥蜴', avatar: '🦎', baseHealth: 100, baseAttack: 30, weakness: '冰', resistance: '火' },
    { name: '冰霜蛛', avatar: '🕷️', baseHealth: 90, baseAttack: 28, weakness: '火', resistance: '冰' },
    { name: '雷鸟', avatar: '🦅', baseHealth: 110, baseAttack: 32, weakness: '风', resistance: '雷' },
    { name: '暗影刺客', avatar: '🥷', baseHealth: 85, baseAttack: 35, weakness: '光', resistance: '暗' }
  ];

  // 开始战斗
  const initiateBattle = () => {
    setBattlePhase('combat');
    setTurnCount(1);
    setBattleTimer(0);
    setPlayerBattleState({
      health: player.health,
      mana: player.mana,
      buffs: [],
      debuffs: []
    });
    
    // 随机生成敌人
    const randomTemplate = enemyTemplates[Math.floor(Math.random() * enemyTemplates.length)];
    const enemyLevel = Math.max(1, player.level - 2 + Math.floor(Math.random() * 5));
    
    const newEnemy: Enemy = {
      id: randomTemplate.name.toLowerCase(),
      name: randomTemplate.name,
      level: enemyLevel,
      health: randomTemplate.baseHealth + (enemyLevel - 1) * 10,
      maxHealth: randomTemplate.baseHealth + (enemyLevel - 1) * 10,
      mana: 40 + (enemyLevel - 1) * 5,
      maxMana: 40 + (enemyLevel - 1) * 5,
      attack: randomTemplate.baseAttack + (enemyLevel - 1) * 3,
      defense: 8 + (enemyLevel - 1) * 2,
      speed: 15 + Math.floor(Math.random() * 10),
      avatar: randomTemplate.avatar,
      skills: ['普通攻击', '特殊技能'],
      weakness: randomTemplate.weakness,
      resistance: randomTemplate.resistance,
      description: `等级 ${enemyLevel} 的强大魔兽`
    };
    
    setCurrentEnemy(newEnemy);
    addLogEntry(`遭遇了 ${newEnemy.name} (等级 ${enemyLevel})！`);
    setIsPlayerTurn(player.speed >= newEnemy.speed); // 根据速度决定先手
  };

  // 显示伤害数字
  const showDamageNumber = (damage: number, type: DamageNumber['type'], target: 'player' | 'enemy') => {
    const id = Math.random().toString(36).substr(2, 9);
    const x = target === 'enemy' ? 70 + Math.random() * 10 : 20 + Math.random() * 10;
    const y = 40 + Math.random() * 20;
    
    setDamageNumbers(prev => [...prev, { id, damage, type, x, y }]);
    
    setTimeout(() => {
      setDamageNumbers(prev => prev.filter(num => num.id !== id));
    }, 2000);
  };

  // 执行玩家动作
  const executePlayerAction = async (action: BattleAction) => {
    if (!isPlayerTurn || isAnimating || battlePhase !== 'combat') return;
    
    setIsAnimating(true);
    setSelectedAction(action);

    // 检查法力值
    const manaCost = action.manaCost || 0;
    if (manaCost > 0 && playerBattleState.mana < manaCost) {
      addLogEntry('法力不足！');
      setIsAnimating(false);
      return;
    }

    let damage = 0;
    let actualDamage = 0;
    let isCritical = false;
    let isMiss = false;

    // 计算伤害
    if (action.type === 'attack' || (action.type === 'skill' && action.damage)) {
      damage = action.damage || player.attack;
      
      // 属性克制计算
      if (action.effect === currentEnemy.weakness) {
        damage = Math.floor(damage * 1.5);
        addLogEntry(`属性克制！伤害提升！`);
      } else if (action.effect === currentEnemy.resistance) {
        damage = Math.floor(damage * 0.7);
        addLogEntry(`敌人抗性！伤害降低！`);
      }

      // 暴击计算
      if (Math.random() < 0.15) {
        damage = Math.floor(damage * 1.8);
        isCritical = true;
      }

      // 命中计算
      if (Math.random() < 0.05) {
        isMiss = true;
        damage = 0;
      }

      // 防御计算
      actualDamage = Math.max(1, damage - currentEnemy.defense);
      
      // 显示伤害数字
      showDamageNumber(actualDamage, isMiss ? 'miss' : isCritical ? 'critical' : 'damage', 'enemy');
    }

    // 执行动作效果
    switch (action.type) {
      case 'attack':
      case 'skill':
        if (action.damage) {
          if (!isMiss) {
            setCurrentEnemy(prev => ({
              ...prev,
              health: Math.max(0, prev.health - actualDamage)
            }));
            
            if (isCritical) {
              addLogEntry(`${action.name} 暴击！造成 ${actualDamage} 点伤害！`);
            } else {
              addLogEntry(`使用 ${action.name}，造成 ${actualDamage} 点伤害！`);
            }
          } else {
            addLogEntry(`${action.name} 未命中！`);
          }
        } else if (action.id === 'meditation') {
          // 冥想恢复法力
          const manaRestore = Math.abs(action.manaCost || 25);
          setPlayerBattleState(prev => ({
            ...prev,
            mana: Math.min(player.maxMana, prev.mana + manaRestore)
          }));
          showDamageNumber(manaRestore, 'heal', 'player');
          addLogEntry(`冥想恢复了 ${manaRestore} 点法力！`);
        }
        break;
        
      case 'defend':
        setPlayerBattleState(prev => ({
          ...prev,
          buffs: [...prev.buffs, { name: '防御姿态', turns: 1, effect: '减少50%伤害' }]
        }));
        addLogEntry('进入防御姿态！');
        break;
    }

    // 消耗法力
    if (manaCost > 0) {
      setPlayerBattleState(prev => ({
        ...prev,
        mana: Math.max(0, prev.mana - manaCost)
      }));
    }

    // 检查敌人是否死亡
    setTimeout(() => {
      const newEnemyHealth = Math.max(0, currentEnemy.health - actualDamage);
      if (newEnemyHealth <= 0) {
        handleVictory();
      } else {
        setIsPlayerTurn(false);
        setTimeout(() => executeEnemyTurn(), 1500);
      }
      setIsAnimating(false);
    }, 1000);
  };

  // 敌人回合
  const executeEnemyTurn = () => {
    if (battlePhase !== 'combat') return;

    console.log('敌人回合开始执行');
    
    const enemyActions = [
      { name: '普通攻击', damage: currentEnemy.attack, probability: 0.6 },
      { name: '重击', damage: Math.floor(currentEnemy.attack * 1.4), probability: 0.25 },
      { name: '特殊技能', damage: Math.floor(currentEnemy.attack * 1.2), probability: 0.15 }
    ];

    const rand = Math.random();
    const selectedAction = rand < 0.6 ? enemyActions[0] : 
                          rand < 0.85 ? enemyActions[1] : enemyActions[2];

    let damage = selectedAction.damage;
    let isCritical = Math.random() < 0.1;
    
    if (isCritical) {
      damage = Math.floor(damage * 1.5);
    }
    
    // 防御姿态减伤
    const hasDefendBuff = playerBattleState.buffs.some(buff => buff.name === '防御姿态');
    if (hasDefendBuff) {
      damage = Math.floor(damage * 0.5);
      addLogEntry('防御姿态减少了伤害！');
    }

    // 玩家防御力减伤
    const actualDamage = Math.max(1, damage - player.defense);
    
    // 计算新的玩家血量
    const newPlayerHealth = Math.max(0, playerBattleState.health - actualDamage);
    
    // 更新玩家状态
    setPlayerBattleState(prev => ({
      ...prev,
      health: newPlayerHealth,
      buffs: prev.buffs.filter(buff => buff.name !== '防御姿态') // 移除防御buff
    }));

    showDamageNumber(actualDamage, isCritical ? 'critical' : 'damage', 'player');
    
    if (isCritical) {
      addLogEntry(`${currentEnemy.name} 使用 ${selectedAction.name} 暴击！造成 ${actualDamage} 点伤害！`);
    } else {
      addLogEntry(`${currentEnemy.name} 使用 ${selectedAction.name}，造成 ${actualDamage} 点伤害！`);
    }

    // 检查玩家是否死亡并切换回合
    setTimeout(() => {
      console.log('检查玩家血量:', newPlayerHealth);
      if (newPlayerHealth <= 0) {
        console.log('玩家死亡，触发失败');
        handleDefeat();
      } else {
        console.log('切换到玩家回合');
        setTurnCount(prev => prev + 1);
        setIsPlayerTurn(true);
      }
    }, 1500);
  };

  // 胜利处理
  const handleVictory = () => {
    setBattlePhase('victory');
    const expGain = Math.floor(currentEnemy.level * 15 + Math.random() * 20);
    const goldGain = Math.floor(currentEnemy.level * 8 + Math.random() * 15);
    
    // 更新玩家经验和金币
    updatePlayer({ experience: player.experience + expGain });
    addGold(goldGain);
    
    addLogEntry(`战斗胜利！获得 ${expGain} 经验值和 ${goldGain} 金币！`);
  };

  // 失败处理
  const handleDefeat = () => {
    setBattlePhase('defeat');
    addLogEntry('战斗失败...');
    // 恢复少量生命值
    updatePlayer({ health: Math.floor(player.maxHealth * 0.1) });
  };

  // 重新开始战斗
  const restartBattle = () => {
    setBattlePhase('preparation');
    setTurnCount(1);
    setBattleTimer(0);
    setSelectedAction(null);
    setDamageNumbers([]);
    setAutoMode(false);
    setBattleLog([]);
    setIsPlayerTurn(true);
    setPlayerBattleState({
      health: player.health,
      mana: player.mana,
      buffs: [],
      debuffs: []
    });
  };

  // 战斗计时器
  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (battlePhase === 'combat') {
      interval = setInterval(() => {
        setBattleTimer(prev => prev + 1);
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [battlePhase]);

  // 自动战斗
  useEffect(() => {
    if (autoMode && isPlayerTurn && battlePhase === 'combat' && !isAnimating) {
      console.log('自动战斗触发，当前状态:', { autoMode, isPlayerTurn, battlePhase, isAnimating });
      
      const availableActions = battleActions.filter(action => 
        !action.manaCost || action.manaCost <= 0 || playerBattleState.mana >= action.manaCost
      );
      
      console.log('可用动作:', availableActions.length);
      
      if (availableActions.length > 0) {
        const randomAction = availableActions[Math.floor(Math.random() * availableActions.length)];
        console.log('选择动作:', randomAction.name);
        
        const timer = setTimeout(() => {
          // 确保在执行前再次检查状态
          if (autoMode && isPlayerTurn && battlePhase === 'combat' && !isAnimating) {
            console.log('执行自动动作:', randomAction.name);
            executePlayerAction(randomAction);
          }
        }, 1000);
        
        // 清理定时器
        return () => clearTimeout(timer);
      }
    }
  }, [autoMode, isPlayerTurn, battlePhase, isAnimating, playerBattleState.mana]);

  // 添加敌人回合强制触发机制
  useEffect(() => {
    if (!isPlayerTurn && battlePhase === 'combat' && !isAnimating) {
      console.log('敌人回合状态检查');
      const timer = setTimeout(() => {
        if (!isPlayerTurn && battlePhase === 'combat' && !isAnimating) {
          console.log('强制触发敌人回合');
          executeEnemyTurn();
        }
      }, 2000);
      
      return () => clearTimeout(timer);
    }
  }, [isPlayerTurn, battlePhase, isAnimating]);

  // 格式化时间
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  return (
    <div className="space-y-6 relative">
      {/* 伤害数字动画 */}
      <AnimatePresence>
        {damageNumbers.map((num) => (
          <motion.div
            key={num.id}
            initial={{ opacity: 1, y: 0, scale: 1 }}
            animate={{ opacity: 0, y: -50, scale: 1.2 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 2 }}
            className={`absolute pointer-events-none font-bold text-xl z-50 ${
              num.type === 'damage' ? 'text-red-400' :
              num.type === 'critical' ? 'text-orange-400' :
              num.type === 'heal' ? 'text-green-400' : 'text-gray-400'
            }`}
            style={{ 
              left: `${num.x}%`, 
              top: `${num.y}%`,
              textShadow: '2px 2px 4px rgba(0,0,0,0.8)'
            }}
          >
            {num.type === 'miss' ? 'MISS' : 
             num.type === 'critical' ? `暴击 ${num.damage}` :
             num.type === 'heal' ? `+${num.damage}` : `-${num.damage}`}
          </motion.div>
        ))}
      </AnimatePresence>

      {/* 战斗标题 */}
      <Card className="bg-slate-800/50 border-slate-700">
        <CardHeader>
          <CardTitle className="text-center text-2xl text-amber-400 flex items-center justify-center gap-2">
            <Sword className="h-6 w-6" />
            修仙战斗
            <Sword className="h-6 w-6" />
          </CardTitle>
          <div className="flex justify-center gap-4 flex-wrap">
            <Badge variant="outline" className="text-blue-400 border-blue-400">
              回合: {turnCount}
            </Badge>
            <Badge variant="outline" className={isPlayerTurn ? "text-green-400 border-green-400" : "text-red-400 border-red-400"}>
              {isPlayerTurn ? "你的回合" : "敌人回合"}
            </Badge>
            <Badge variant="outline" className="text-purple-400 border-purple-400">
              {battlePhase === 'preparation' ? '准备中' : 
               battlePhase === 'combat' ? '战斗中' :
               battlePhase === 'victory' ? '胜利' : '失败'}
            </Badge>
            {battlePhase === 'combat' && (
              <Badge variant="outline" className="text-cyan-400 border-cyan-400">
                <Clock className="h-3 w-3 mr-1" />
                {formatTime(battleTimer)}
              </Badge>
            )}
          </div>
        </CardHeader>
      </Card>

      {battlePhase === 'preparation' && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center space-y-6"
        >
          <Card className="bg-slate-800/50 border-slate-700">
            <CardContent className="pt-6">
              <div className="space-y-4">
                <div className="text-6xl mb-4">⚔️</div>
                <h3 className="text-xl text-slate-100">准备进入战斗</h3>
                <p className="text-slate-400">
                  在这片危险的修仙世界中，随时可能遭遇强大的妖兽。
                  运用你的修为和技能，击败敌人获得经验和奖励！
                </p>
                <div className="grid grid-cols-2 gap-4 text-sm text-slate-300">
                  <div className="bg-slate-700/50 rounded p-3">
                    <div className="text-amber-400 font-semibold mb-1">战斗提示</div>
                    <div>• 合理使用技能和法力</div>
                    <div>• 注意属性克制关系</div>
                    <div>• 防御可以减少伤害</div>
                  </div>
                  <div className="bg-slate-700/50 rounded p-3">
                    <div className="text-green-400 font-semibold mb-1">胜利奖励</div>
                    <div>• 获得经验值提升等级</div>
                    <div>• 获得金币购买装备</div>
                    <div>• 提升战斗技巧</div>
                  </div>
                </div>
                <Button 
                  onClick={initiateBattle}
                  className="bg-red-600 hover:bg-red-700"
                  size="lg"
                  disabled={player.health <= 0}
                >
                  <Target className="h-4 w-4 mr-2" />
                  寻找对手
                </Button>
                {player.health <= 0 && (
                  <Alert className="border-red-600 bg-red-900/20">
                    <AlertTriangle className="h-4 w-4 text-red-400" />
                    <AlertDescription className="text-red-400">
                      生命值不足，请先恢复生命值再进行战斗！
                    </AlertDescription>
                  </Alert>
                )}
              </div>
            </CardContent>
          </Card>
        </motion.div>
      )}

      {battlePhase === 'combat' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 玩家状态 */}
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-green-400 flex items-center gap-2">
                <div className="text-2xl">{player.avatar}</div>
                <div>
                  <div>{player.name}</div>
                  <div className="text-sm text-slate-400">等级 {player.level} • {player.realm.name}</div>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-slate-400">生命值</span>
                  <span className="text-red-400">{playerBattleState.health}/{player.maxHealth}</span>
                </div>
                <Progress 
                  value={(playerBattleState.health / player.maxHealth) * 100} 
                  className="h-3 bg-slate-700"
                />
              </div>

              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-slate-400">法力值</span>
                  <span className="text-blue-400">{playerBattleState.mana}/{player.maxMana}</span>
                </div>
                <Progress 
                  value={(playerBattleState.mana / player.maxMana) * 100} 
                  className="h-3 bg-slate-700"
                />
              </div>

              <Separator className="bg-slate-600" />

              <div className="space-y-2">
                <div className="text-sm text-slate-400">属性</div>
                <div className="grid grid-cols-2 gap-2 text-xs">
                  <div className="flex justify-between">
                    <span className="text-slate-500">攻击:</span>
                    <span className="text-red-400">{player.attack}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">防御:</span>
                    <span className="text-blue-400">{player.defense}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">速度:</span>
                    <span className="text-green-400">{player.speed}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">境界:</span>
                    <span className="text-amber-400">{player.realm.name}</span>
                  </div>
                </div>
              </div>

              {/* Buff/Debuff 显示 */}
              {(playerBattleState.buffs.length > 0 || playerBattleState.debuffs.length > 0) && (
                <div className="space-y-2">
                  <div className="text-sm text-slate-400">状态效果</div>
                  {playerBattleState.buffs.map((buff, index) => (
                    <Badge key={index} className="bg-green-600 text-white text-xs mr-1">
                      {buff.name} ({buff.turns}回合)
                    </Badge>
                  ))}
                  {playerBattleState.debuffs.map((debuff, index) => (
                    <Badge key={index} className="bg-red-600 text-white text-xs mr-1">
                      {debuff.name} ({debuff.turns}回合)
                    </Badge>
                  ))}
                </div>
              )}

              {/* 战斗动作 */}
              <div className="space-y-2">
                <div className="text-sm text-slate-400">战斗动作</div>
                <div className="grid grid-cols-2 gap-2">
                  {battleActions.slice(0, 6).map((action) => (
                    <Button
                      key={action.id}
                      onClick={() => executePlayerAction(action)}
                      disabled={
                        !isPlayerTurn || 
                        isAnimating || 
                        Boolean(action.manaCost && action.manaCost > 0 && playerBattleState.mana < action.manaCost)
                      }
                      className={`h-auto p-2 text-xs ${
                        action.manaCost && action.manaCost > 0 && playerBattleState.mana < action.manaCost
                          ? 'bg-slate-600 text-slate-500 cursor-not-allowed' 
                          : 'bg-slate-700 hover:bg-slate-600 text-slate-100'
                      }`}
                      variant="ghost"
                    >
                      <div className="flex flex-col items-center gap-1">
                        <div className={action.color}>{action.icon}</div>
                        <div className="text-xs">{action.name}</div>
                        {action.manaCost && action.manaCost > 0 && (
                          <div className="text-blue-400 text-xs">{action.manaCost}</div>
                        )}
                      </div>
                    </Button>
                  ))}
                </div>
              </div>

              <div className="flex gap-2">
                <Button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    setAutoMode(!autoMode);
                  }}
                  variant="outline"
                  size="sm"
                  className={`flex-1 border-slate-600 ${autoMode ? 'text-green-400 border-green-400' : 'text-slate-300'}`}
                  disabled={battlePhase !== 'combat'}
                >
                  {autoMode ? <Pause className="h-3 w-3 mr-1" /> : <Play className="h-3 w-3 mr-1" />}
                  {autoMode ? '暂停' : '自动'}
                </Button>
                <Button
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    restartBattle();
                  }}
                  variant="outline"
                  size="sm"
                  className="border-slate-600 text-slate-300"
                >
                  <RotateCcw className="h-3 w-3 mr-1" />
                  撤退
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* 战斗场景 */}
          <Card className="bg-slate-800/50 border-slate-700">
            <CardContent className="pt-6">
              <div className="text-center space-y-4">
                <div className="relative">
                  <motion.div
                    animate={isPlayerTurn && selectedAction ? { scale: [1, 1.1, 1] } : {}}
                    transition={{ duration: 0.5 }}
                    className="text-4xl mb-2"
                  >
                    {player.avatar}
                  </motion.div>
                  <div className="text-2xl text-amber-400 my-4">⚔️</div>
                  <motion.div
                    animate={!isPlayerTurn ? { scale: [1, 1.1, 1] } : {}}
                    transition={{ duration: 0.5 }}
                    className="text-4xl mt-2"
                  >
                    {currentEnemy.avatar}
                  </motion.div>
                </div>
                
                {selectedAction && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.8 }}
                    className="bg-slate-700/50 rounded-lg p-3"
                  >
                    <div className="flex items-center justify-center gap-2 text-slate-200">
                      {selectedAction.icon}
                      <span className="font-semibold">{selectedAction.name}</span>
                    </div>
                    <div className="text-sm text-slate-400 mt-1">
                      {selectedAction.description}
                    </div>
                  </motion.div>
                )}

                <div className="text-lg text-amber-400 font-semibold">
                  {isAnimating ? '施展中...' : isPlayerTurn ? '等待你的行动' : '敌人思考中...'}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 敌人状态 */}
          <Card className="bg-slate-800/50 border-slate-700">
            <CardHeader>
              <CardTitle className="text-red-400 flex items-center gap-2">
                <div className="text-2xl">{currentEnemy.avatar}</div>
                <div>
                  <div>{currentEnemy.name}</div>
                  <div className="text-sm text-slate-400">等级 {currentEnemy.level}</div>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-slate-400">生命值</span>
                  <span className="text-red-400">{currentEnemy.health}/{currentEnemy.maxHealth}</span>
                </div>
                <Progress 
                  value={(currentEnemy.health / currentEnemy.maxHealth) * 100} 
                  className="h-3 bg-slate-700"
                />
              </div>

              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-slate-400">法力值</span>
                  <span className="text-blue-400">{currentEnemy.mana}/{currentEnemy.maxMana}</span>
                </div>
                <Progress 
                  value={(currentEnemy.mana / currentEnemy.maxMana) * 100} 
                  className="h-3 bg-slate-700"
                />
              </div>

              <Separator className="bg-slate-600" />

              <div className="space-y-2">
                <div className="text-sm text-slate-400">属性信息</div>
                <div className="grid grid-cols-2 gap-2 text-xs">
                  <div className="flex justify-between">
                    <span className="text-slate-500">攻击:</span>
                    <span className="text-red-400">{currentEnemy.attack}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">防御:</span>
                    <span className="text-blue-400">{currentEnemy.defense}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">速度:</span>
                    <span className="text-green-400">{currentEnemy.speed}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-slate-500">等级:</span>
                    <span className="text-amber-400">{currentEnemy.level}</span>
                  </div>
                </div>
              </div>

              {currentEnemy.weakness && currentEnemy.resistance && (
                <div className="space-y-2">
                  <div className="text-sm text-slate-400">属性关系</div>
                  <div className="flex gap-2">
                    <Badge className="bg-green-600 text-white text-xs">
                      弱点: {currentEnemy.weakness}
                    </Badge>
                    <Badge className="bg-red-600 text-white text-xs">
                      抗性: {currentEnemy.resistance}
                    </Badge>
                  </div>
                </div>
              )}

              <div className="text-xs text-slate-500">
                {currentEnemy.description}
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 战斗日志 */}
      {battlePhase === 'combat' && (
        <Card className="bg-slate-800/50 border-slate-700">
          <CardHeader>
            <CardTitle className="text-slate-100 flex items-center gap-2">
              <ScrollArea className="h-4 w-4" />
              战斗记录
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-32 bg-slate-900/50 rounded p-3">
              <div className="space-y-1">
                {battleLog && battleLog.length > 0 ? battleLog.map((log, index) => (
                  <motion.div
                    key={index}
                    initial={{ opacity: 0, x: -20 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: index * 0.1 }}
                    className="text-sm text-slate-300"
                  >
                    <span className="text-slate-500">[{index + 1}]</span> {log}
                  </motion.div>
                )) : (
                  <div className="text-sm text-slate-500">等待战斗开始...</div>
                )}
              </div>
            </ScrollArea>
          </CardContent>
        </Card>
      )}

      {/* 胜利界面 */}
      {battlePhase === 'victory' && (
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center space-y-6"
        >
          <Card className="bg-gradient-to-r from-green-800/50 to-green-700/50 border-green-600">
            <CardContent className="pt-6">
              <div className="space-y-4">
                <div className="text-6xl mb-4">🎉</div>
                <h3 className="text-2xl text-green-400 font-bold">战斗胜利！</h3>
                <p className="text-slate-300">
                  你成功击败了 {currentEnemy.name}，获得了丰厚的奖励！
                </p>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div className="bg-slate-700/50 rounded p-3">
                    <div className="text-amber-400 font-semibold mb-1">
                      <Star className="h-4 w-4 inline mr-1" />
                      经验奖励
                    </div>
                    <div className="text-slate-300">
                      +{Math.floor(currentEnemy.level * 15 + Math.random() * 20)} 经验值
                    </div>
                  </div>
                  <div className="bg-slate-700/50 rounded p-3">
                    <div className="text-yellow-400 font-semibold mb-1">
                      <Sparkles className="h-4 w-4 inline mr-1" />
                      金币奖励
                    </div>
                    <div className="text-slate-300">
                      +{Math.floor(currentEnemy.level * 8 + Math.random() * 15)} 金币
                    </div>
                  </div>
                </div>
                <div className="flex gap-3 justify-center">
                  <Button 
                    onClick={initiateBattle}
                    className="bg-red-600 hover:bg-red-700"
                  >
                    <Target className="h-4 w-4 mr-2" />
                    继续战斗
                  </Button>
                  <Button 
                    onClick={restartBattle}
                    variant="outline"
                    className="border-slate-600 text-slate-300"
                  >
                    <CheckCircle className="h-4 w-4 mr-2" />
                    返回准备
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </motion.div>
      )}

      {/* 失败界面 */}
      {battlePhase === 'defeat' && (
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center space-y-6"
        >
          <Card className="bg-gradient-to-r from-red-800/50 to-red-700/50 border-red-600">
            <CardContent className="pt-6">
              <div className="space-y-4">
                <div className="text-6xl mb-4">💀</div>
                <h3 className="text-2xl text-red-400 font-bold">战斗失败</h3>
                <p className="text-slate-300">
                  你被 {currentEnemy.name} 击败了，但这只是修仙路上的一次挫折。
                </p>
                <Alert className="border-amber-600 bg-amber-900/20">
                  <AlertTriangle className="h-4 w-4 text-amber-400" />
                  <AlertDescription className="text-amber-400">
                    失败后恢复了少量生命值，继续努力修炼吧！
                  </AlertDescription>
                </Alert>
                <div className="flex gap-3 justify-center">
                  <Button 
                    onClick={restartBattle}
                    className="bg-blue-600 hover:bg-blue-700"
                  >
                    <RotateCcw className="h-4 w-4 mr-2" />
                    重新准备
                  </Button>
                  <Button 
                    onClick={() => window.history.back()}
                    variant="outline"
                    className="border-slate-600 text-slate-300"
                  >
                    返回主页
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </motion.div>
      )}
    </div>
  );
}
